using System;
using System.Collections.Specialized;
using System.Linq;
using Microsoft.Practices.Composite.Presentation.Regions;
using PrismNavigationFramework.Navigation;
using PrismNavigationFramework.Navigation.Controls;

namespace PrismNavigationFramework.RegionBehaviors
{
    public class PrismNavigationMainFrameRegionBehavior : RegionBehavior
    {
        private readonly IPrismNavigationConfiguration _prismNavigationConfiguration;

        public PrismNavigationMainFrameRegionBehavior(IPrismNavigationConfiguration prismNavigationConfiguration)
        {
            _prismNavigationConfiguration = prismNavigationConfiguration;
        }

        public const string BehaviorKey = "PrismNavigationMainFrameRegionBehavior";

        public PrismNavigationMainFrame HostFrame { get; set; }

        protected override void OnAttach()
        {
            if (this.HostFrame == null)
            {
                throw new InvalidOperationException("No HostFrame defined in region.");
            }

            this.Region.ActiveViews.CollectionChanged += this.OnActiveViewsChanged;

            var regionName = this.HostFrame.GetValue(RegionManager.RegionNameProperty) as string;
            if (!string.IsNullOrEmpty(regionName))
            {
                this.HostFrame.Name = regionName;
                this._prismNavigationConfiguration.MainRegionName = regionName;
            }
        }

        private void OnActiveViewsChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            var lastViewAdded = this.Region.ActiveViews.LastOrDefault();
            if (lastViewAdded != null)
            {
                this.HostFrame.Content = lastViewAdded;
            }
        }
    }
}